// 弹窗脚本 - 处理用户界面交互
class PopupManager {
  constructor() {
    this.currentTab = 'favorites'; // 默认显示收藏页面
    this.settings = {};
    this.history = [];
    this.favorites = [];
    this.init();
  }

  async init() {
    await this.loadSettings();
    this.bindEvents();
    this.loadData();
  }

  async loadSettings() {
    try {
      const response = await chrome.runtime.sendMessage({ type: 'getSettings' });
      this.settings = response;
      this.updateSettingsUI();
    } catch (error) {
      console.error('加载设置失败:', error);
    }
  }

  updateSettingsUI() {
    // 更新自动翻译开关
    const autoTranslateToggle = document.getElementById('auto-translate-toggle');
    if (autoTranslateToggle) {
      autoTranslateToggle.checked = this.settings.autoTranslate !== false;
    }

    // 更新翻译服务选择
    const translationService = document.getElementById('translation-service');
    if (translationService) {
      translationService.value = this.settings.currentAPI || 'bing';
      if (!this.settings.currentAPI) {
        this.settings.currentAPI = 'bing';
      }
    }

    // 更新API配置显示
    this.updateAPIConfigDisplay();

    // 填充API密钥
    this.fillAPIKeys();
  }

  updateAPIConfigDisplay() {
    const currentService = this.settings.currentAPI || 'bing';
    const configs = ['baidu-config', 'chrome-config', 'tencent-config', 'google-config', 'deepl-config', 'bing-config', 'youdao-config'];
    
    configs.forEach(configId => {
      const config = document.getElementById(configId);
      if (config) {
        config.style.display = configId === `${currentService}-config` ? 'block' : 'none';
      }
    });
  }

  fillAPIKeys() {
    if (this.settings.apiKeys) {
      // 百度翻译
      if (this.settings.apiKeys.baidu) {
        const baiduAppId = document.getElementById('baidu-app-id');
        const baiduSecretKey = document.getElementById('baidu-secret-key');
        if (baiduAppId) baiduAppId.value = this.settings.apiKeys.baidu.appId || '';
        if (baiduSecretKey) baiduSecretKey.value = this.settings.apiKeys.baidu.secretKey || '';
      }
      
      // 腾讯翻译
      if (this.settings.apiKeys.tencent) {
        const tencentSecretId = document.getElementById('tencent-secret-id');
        const tencentSecretKey = document.getElementById('tencent-secret-key');
        if (tencentSecretId) tencentSecretId.value = this.settings.apiKeys.tencent.secretId || '';
        if (tencentSecretKey) tencentSecretKey.value = this.settings.apiKeys.tencent.secretKey || '';
      }
      
      // Google翻译
      if (this.settings.apiKeys.google) {
        const googleKey = document.getElementById('google-api-key');
        if (googleKey) googleKey.value = this.settings.apiKeys.google;
      }
      
      // DeepL翻译
      if (this.settings.apiKeys.deepl) {
        const deeplKey = document.getElementById('deepl-api-key');
        if (deeplKey) deeplKey.value = this.settings.apiKeys.deepl;
      }
      
      // Bing翻译
      // if (this.settings.apiKeys.bing) {
      //   const bingKey = document.getElementById('bing-api-key');
      //   if (bingKey) bingKey.value = this.settings.apiKeys.bing;
      // }
      

    }
  }

  bindEvents() {
    // 标签切换
    document.querySelectorAll('.tab-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const tab = e.target.dataset.tab;
        this.switchTab(tab);
      });
    });





    // 设置相关
    const translationService = document.getElementById('translation-service');
    if (translationService) {
      translationService.addEventListener('change', () => {
        this.settings.currentAPI = translationService.value;
        this.updateAPIConfigDisplay();
      });
    }

    const saveSettingsBtn = document.getElementById('save-settings-btn');
    const testApiBtn = document.getElementById('test-api-btn');

    if (saveSettingsBtn) {
      saveSettingsBtn.addEventListener('click', () => this.saveSettings());
    }

    if (testApiBtn) {
      testApiBtn.addEventListener('click', () => this.testAPI());
    }

    // 历史记录操作
    const exportHistoryBtn = document.getElementById('export-history-btn');
    const clearHistoryBtn = document.getElementById('clear-history-btn');
    const historySearch = document.getElementById('history-search');

    if (exportHistoryBtn) {
      exportHistoryBtn.addEventListener('click', () => this.exportHistory());
    }

    if (clearHistoryBtn) {
      clearHistoryBtn.addEventListener('click', () => this.clearHistory());
    }

    if (historySearch) {
      historySearch.addEventListener('input', (e) => this.searchHistory(e.target.value));
    }

    // 收藏夹操作
    const exportFavoritesBtn = document.getElementById('export-favorites-btn');
    const clearFavoritesBtn = document.getElementById('clear-favorites-btn');
    const favoritesSearch = document.getElementById('favorites-search');

    if (exportFavoritesBtn) {
      exportFavoritesBtn.addEventListener('click', () => this.exportFavorites());
    }

    if (clearFavoritesBtn) {
      clearFavoritesBtn.addEventListener('click', () => this.clearFavorites());
    }

    if (favoritesSearch) {
      favoritesSearch.addEventListener('input', (e) => this.searchFavorites(e.target.value));
    }



    // 收藏夹项目操作事件委托
    document.addEventListener('click', (e) => {
      if (e.target.closest('.edit-favorite-btn')) {
        e.stopPropagation();
        const favoriteItem = e.target.closest('.favorite-item');
        this.editFavoriteItem(favoriteItem);
      } else if (e.target.closest('.copy-item-btn')) {
        e.stopPropagation();
        const item = e.target.closest('.favorite-item, .history-item');
        this.copyItem(item);
      } else if (e.target.closest('.remove-favorite-btn')) {
        e.stopPropagation();
        const favoriteItem = e.target.closest('.favorite-item');
        this.removeFavoriteItem(favoriteItem);
      }
    });

    // 历史记录项目操作
    document.addEventListener('click', (e) => {
      if (e.target.closest('.favorite-item-btn')) {
        const item = e.target.closest('.history-item');
        if (item) this.favoriteHistoryItem(item);
      }
    });
  }

  switchTab(tabName) {
    // 更新标签按钮状态
    document.querySelectorAll('.tab-btn').forEach(btn => {
      btn.classList.toggle('active', btn.dataset.tab === tabName);
    });

    // 更新标签内容
    document.querySelectorAll('.tab-content').forEach(content => {
      content.classList.toggle('active', content.id === `${tabName}-tab`);
    });

    this.currentTab = tabName;

    // 加载对应数据
    if (tabName === 'history') {
      this.loadHistory();
    } else if (tabName === 'favorites') {
      this.loadFavorites();
    }
  }







  async saveSettings() {
    const autoTranslate = document.getElementById('auto-translate-toggle').checked;
    const currentAPI = document.getElementById('translation-service').value;
    
    const apiKeys = {
      baidu: {
        appId: document.getElementById('baidu-app-id').value,
        secretKey: document.getElementById('baidu-secret-key').value
      },
      tencent: {
        secretId: document.getElementById('tencent-secret-id').value,
        secretKey: document.getElementById('tencent-secret-key').value
      },
      google: document.getElementById('google-api-key').value,
      deepl: document.getElementById('deepl-api-key').value,

    };

    const settings = {
      autoTranslate,
      currentAPI,
      apiKeys
    };

    try {
      await chrome.runtime.sendMessage({
        type: 'updateSettings',
        settings: settings
      });

      this.settings = settings;
      this.showMessage('设置已保存', 'success');
    } catch (error) {
      this.showMessage('保存设置失败: ' + error.message, 'error');
    }
  }

  async testAPI() {
    const currentAPI = this.settings.currentAPI || 'bing';
    const apiKeys = this.settings.apiKeys;

    if (!apiKeys || !apiKeys[currentAPI]) {
      this.showMessage('请先配置API密钥', 'warning');
      return;
    }

    try {
      const response = await chrome.runtime.sendMessage({
        type: 'translate',
        text: 'Hello',
        fromLang: 'en',
        toLang: 'zh'
      });

      if (response.error) {
        this.showMessage('API测试失败: ' + response.error, 'error');
      } else {
        this.showMessage('API测试成功', 'success');
      }
    } catch (error) {
      this.showMessage('API测试失败: ' + error.message, 'error');
    }
  }

  async loadData() {
    await this.loadHistory();
    await this.loadFavorites();
  }

  async loadHistory() {
    try {
      const response = await chrome.runtime.sendMessage({ type: 'getHistory' });
      this.history = response;
      this.renderHistory();
    } catch (error) {
      console.error('加载历史记录失败:', error);
    }
  }

  async loadFavorites() {
    try {
      const response = await chrome.runtime.sendMessage({ type: 'getFavorites' });
      this.favorites = response;
      this.renderFavorites();
    } catch (error) {
      console.error('加载收藏失败:', error);
    }
  }

  renderHistory() {
    const historyList = document.getElementById('history-list');
    if (!historyList) return;

    historyList.innerHTML = '';

    if (this.history.length === 0) {
      historyList.innerHTML = '<div class="empty-state">暂无历史记录</div>';
      return;
    }

    this.history.forEach(item => {
      const historyItem = this.createHistoryItem(item);
      historyList.appendChild(historyItem);
    });
  }

  renderFavorites() {
    const favoritesList = document.getElementById('favorites-list');
    if (!favoritesList) return;

    favoritesList.innerHTML = '';

    if (this.favorites.length === 0) {
      favoritesList.innerHTML = '<div class="empty-state">暂无收藏</div>';
      return;
    }

    this.favorites.forEach(item => {
      const favoriteItem = this.createFavoriteItem(item);
      favoritesList.appendChild(favoriteItem);
    });
  }

  createHistoryItem(item) {
    const template = document.getElementById('history-item-template');
    const clone = template.content.cloneNode(true);

    clone.querySelector('.original-item').textContent = item.originalText;
    clone.querySelector('.translated-item').textContent = item.translatedText;
    clone.querySelector('.service-item').textContent = this.getServiceDisplayName(item.service);
    clone.querySelector('.time-item').textContent = new Date(item.timestamp).toLocaleString();

    const historyItem = clone.querySelector('.history-item');
    historyItem.dataset.id = item.id;

    return clone;
  }

  createFavoriteItem(item) {
    const template = document.getElementById('favorite-item-template');
    const clone = template.content.cloneNode(true);

    clone.querySelector('.original-item').textContent = item.originalText;
    clone.querySelector('.translated-item').textContent = item.translatedText;
    clone.querySelector('.service-item').textContent = this.getServiceDisplayName(item.service);
    clone.querySelector('.time-item').textContent = new Date(item.timestamp).toLocaleString();

    const favoriteItem = clone.querySelector('.favorite-item');
    favoriteItem.dataset.id = item.id;

    // 添加单击编辑功能
    const itemContent = favoriteItem.querySelector('.item-content');
    itemContent.addEventListener('click', () => {
      this.editFavoriteItem(favoriteItem);
    });

    return clone;
  }

  async favoriteHistoryItem(item) {
    const id = item.dataset.id;
    const historyItem = this.history.find(h => h.id === id);
    
    if (historyItem) {
      try {
        await chrome.runtime.sendMessage({
          type: 'saveFavorite',
          data: historyItem
        });

        this.showMessage('已添加到收藏', 'success');
      } catch (error) {
        this.showMessage('收藏失败: ' + error.message, 'error');
      }
    }
  }

  async copyItem(item) {
    const translatedText = item.querySelector('.translated-item').textContent;
    
    try {
      await navigator.clipboard.writeText(translatedText);
      this.showMessage('已复制到剪贴板', 'success');
    } catch (error) {
      const textArea = document.createElement('textarea');
      textArea.value = translatedText;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
      this.showMessage('已复制到剪贴板', 'success');
    }
  }

  async removeFavoriteItem(item) {
    const id = item.dataset.id;
    
    if (confirm('确定要删除这个收藏吗？')) {
      try {
        await chrome.runtime.sendMessage({
          type: 'removeFavorite',
          id: id
        });

        this.loadFavorites();
        this.showMessage('已删除收藏', 'success');
      } catch (error) {
        this.showMessage('删除失败: ' + error.message, 'error');
      }
    }
  }

  async clearHistory() {
    if (confirm('确定要清空所有历史记录吗？此操作不可恢复。')) {
      try {
        await chrome.storage.local.remove('history');
        this.history = [];
        this.renderHistory();
        this.showMessage('历史记录已清空', 'success');
      } catch (error) {
        this.showMessage('清空失败: ' + error.message, 'error');
      }
    }
  }

  async clearFavorites() {
    if (confirm('确定要清空所有收藏吗？此操作不可恢复。')) {
      try {
        await chrome.runtime.sendMessage({ type: 'clearFavorites' });
        this.favorites = [];
        this.renderFavorites();
        this.showMessage('收藏已清空', 'success');
      } catch (error) {
        this.showMessage('清空失败: ' + error.message, 'error');
      }
    }
  }

  async exportFavorites() {
    try {
      const response = await chrome.runtime.sendMessage({ type: 'exportFavorites' });
      
      if (response.csvContent) {
        const blob = new Blob([response.csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        
        link.setAttribute('href', url);
        link.setAttribute('download', `翻译收藏_${new Date().toISOString().split('T')[0]}.csv`);
        link.style.visibility = 'hidden';
        
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        this.showMessage('收藏已导出', 'success');
      }
    } catch (error) {
      this.showMessage('导出失败: ' + error.message, 'error');
    }
  }

  async exportHistory() {
    try {
      const response = await chrome.runtime.sendMessage({ type: 'exportHistory' });
      if (response.csvContent) {
        const blob = new Blob([response.csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', `翻译历史_${new Date().toISOString().split('T')[0]}.csv`);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.showMessage('历史已导出', 'success');
      }
    } catch (error) {
      this.showMessage('导出失败: ' + error.message, 'error');
    }
  }

  searchHistory(query) {
    const filteredHistory = this.history.filter(item => 
      item.originalText.toLowerCase().includes(query.toLowerCase()) ||
      item.translatedText.toLowerCase().includes(query.toLowerCase())
    );

    this.renderFilteredHistory(filteredHistory);
  }

  searchFavorites(query) {
    const filteredFavorites = this.favorites.filter(item => 
      item.originalText.toLowerCase().includes(query.toLowerCase()) ||
      item.translatedText.toLowerCase().includes(query.toLowerCase())
    );

    this.renderFilteredFavorites(filteredFavorites);
  }

  renderFilteredHistory(filteredHistory) {
    const historyList = document.getElementById('history-list');
    if (!historyList) return;

    historyList.innerHTML = '';

    if (filteredHistory.length === 0) {
      historyList.innerHTML = '<div class="empty-state">未找到匹配的历史记录</div>';
      return;
    }

    filteredHistory.forEach(item => {
      const historyItem = this.createHistoryItem(item);
      historyList.appendChild(historyItem);
    });
  }

  renderFilteredFavorites(filteredFavorites) {
    const favoritesList = document.getElementById('favorites-list');
    if (!favoritesList) return;

    favoritesList.innerHTML = '';

    if (filteredFavorites.length === 0) {
      favoritesList.innerHTML = '<div class="empty-state">未找到匹配的收藏</div>';
      return;
    }

    filteredFavorites.forEach(item => {
      const favoriteItem = this.createFavoriteItem(item);
      favoritesList.appendChild(favoriteItem);
    });
  }

  getServiceDisplayName(service) {
    const serviceNames = {
      'baidu': '百度翻译',
      'chrome': 'Chrome翻译',
      'tencent': '腾讯翻译君',
      'google': 'Google翻译',
      'deepl': 'DeepL翻译',
      'bing': 'Bing翻译',
      'youdao': '有道词典'
    };
    return serviceNames[service] || service;
  }

  showMessage(message, type = 'info') {
    // 创建消息提示
    const messageEl = document.createElement('div');
    messageEl.className = `message message-${type}`;
    messageEl.textContent = message;
    messageEl.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 8px 16px;
      border-radius: 4px;
      color: white;
      font-size: 12px;
      z-index: 10000;
      animation: slideIn 0.3s ease;
    `;

    // 根据类型设置背景色
    const colors = {
      success: '#4CAF50',
      error: '#f44336',
      warning: '#ff9800',
      info: '#2196F3'
    };
    messageEl.style.background = colors[type] || colors.info;

    document.body.appendChild(messageEl);

    // 3秒后自动移除
    setTimeout(() => {
      messageEl.style.animation = 'slideOut 0.3s ease';
      setTimeout(() => {
        if (messageEl.parentNode) {
          messageEl.parentNode.removeChild(messageEl);
        }
      }, 300);
    }, 3000);
  }

  editFavoriteItem(item) {
    // 进入编辑模式
    const original = item.querySelector('.original-item');
    const translated = item.querySelector('.translated-item');
    const originalText = original.textContent;
    const translatedText = translated.textContent;
    
    // 原文保持只读，只编辑译文
    original.innerHTML = `<span class="readonly-original">${originalText}</span>`;
    translated.innerHTML = `<input class="edit-translated-input" value="${translatedText}">`;
    
    // 替换操作按钮为保存/取消按钮
    const actions = item.querySelector('.item-actions');
    actions.innerHTML = `
      <button class="save-edit-btn" title="保存" style="color: #4CAF50;">✓</button>
      <button class="cancel-edit-btn" title="取消" style="color: #f44336;">✗</button>
    `;
    actions.style.display = 'flex';
    
    // 绑定保存和取消按钮事件
    const saveBtn = actions.querySelector('.save-edit-btn');
    const cancelBtn = actions.querySelector('.cancel-edit-btn');
    
    saveBtn.addEventListener('click', (e) => {
      e.stopPropagation();
      if (blurTimeout) {
        clearTimeout(blurTimeout);
      }
      this.saveFavoriteEdit(item);
    });
    
    cancelBtn.addEventListener('click', (e) => {
      e.stopPropagation();
      this.loadFavorites(); // 直接重新加载，不保存
    });
    
    // 获取输入框
    const translatedInput = item.querySelector('.edit-translated-input');
    
    // 标记正在编辑状态
    item.dataset.editing = 'true';
    
    // 添加失去焦点时自动保存（延迟执行，给用户时间点击保存按钮）
    let blurTimeout;
    const saveOnBlur = (e) => {
      // 检查是否点击了当前项目内的其他元素
      const relatedTarget = e.relatedTarget;
      if (relatedTarget && item.contains(relatedTarget)) {
        return;
      }
      
      // 延迟保存，给用户时间点击保存按钮
      blurTimeout = setTimeout(() => {
        this.saveFavoriteEdit(item);
        translatedInput.removeEventListener('blur', saveOnBlur);
      }, 300);
    };
    
    translatedInput.addEventListener('blur', saveOnBlur);
    
    // 添加回车键保存
    const saveOnEnter = (e) => {
      if (e.key === 'Enter') {
        e.preventDefault();
        this.saveFavoriteEdit(item);
        translatedInput.removeEventListener('keydown', saveOnEnter);
      }
    };
    
    translatedInput.addEventListener('keydown', saveOnEnter);
    
    // 设置焦点到译文输入框并选中文本
    translatedInput.focus();
    translatedInput.select();
  }

  async saveFavoriteEdit(item) {
    const id = item.dataset.id;
    const originalText = item.querySelector('.readonly-original').textContent;
    const translatedInput = item.querySelector('.edit-translated-input');
    const newTranslated = translatedInput.value.trim();
    
    if (!newTranslated) {
      this.showMessage('译文不能为空', 'warning');
      // 恢复原始内容
      this.loadFavorites();
      return;
    }
    
    try {
      await chrome.runtime.sendMessage({
        type: 'updateFavorite',
        id,
        originalText: originalText,
        translatedText: newTranslated
      });
      this.showMessage('已保存修改', 'success');
      this.loadFavorites();
    } catch (error) {
      this.showMessage('保存失败: ' + error.message, 'error');
      // 恢复原始内容
      this.loadFavorites();
    } finally {
      // 清理编辑状态
      if (item.dataset.editing) {
        delete item.dataset.editing;
      }
    }
  }


}

// 添加动画样式
const style = document.createElement('style');
style.textContent = `
  @keyframes slideIn {
    from {
      transform: translateX(100%);
      opacity: 0;
    }
    to {
      transform: translateX(0);
      opacity: 1;
    }
  }
  
  @keyframes slideOut {
    from {
      transform: translateX(0);
      opacity: 1;
    }
    to {
      transform: translateX(100%);
      opacity: 0;
    }
  }
  
  .empty-state {
    text-align: center;
    color: #999;
    padding: 40px 20px;
    font-size: 14px;
  }
`;
document.head.appendChild(style);

// 初始化弹窗管理器
const popupManager = new PopupManager(); 